package com.uam.core.dao.mysql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import com.uam.core.entity.uitls.ZipUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.uam.core.entity.model.TaskModel;
import com.uam.core.entity.model.TaskQueryResult;
import com.uam.core.entity.uitls.StringUtil;

import lombok.extern.slf4j.Slf4j;

@Repository
@Slf4j
public class TaskDao {

	@Autowired
	private JdbcTemplate jdbcTemplate = null;
	private String talbeName="TASK";

	private Cache<Integer, TaskQueryResult> cache = Caffeine.newBuilder().expireAfterAccess(128, TimeUnit.MINUTES)
			.maximumSize(65536).build();

	public int updateTaskName(int id, String name) {
		TaskDao.log.info("---------修改任务名称，id:{}，name:{}---------", id, name);
		return this.jdbcTemplate.update(con -> {
			PreparedStatement ps = con.prepareStatement("UPDATE `"+talbeName+"` SET `NAME`=?,`UPDATE_TIME`=? WHERE `ID`=?");
			ps.setString(1, name);
			ps.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
			ps.setInt(3, id);
			return ps;
		});
	}

	public int updateTaskStatus(int id, int status) {
		TaskDao.log.info("---------修改任务状态，id:{}，status:{}---------", id, status);
		return this.jdbcTemplate.update(con -> {
			PreparedStatement ps = con.prepareStatement("UPDATE `"+talbeName+"` SET `STATUS`=? WHERE `ID`=?");
			ps.setInt(1, status);
			ps.setInt(2, id);
			return ps;
		});
	}

	public int rejectTask(int id, String remark) {
		TaskDao.log.info("---------拒绝任务，id:{}，remark:{}---------", id, remark);
		return this.jdbcTemplate.update(con -> {
			PreparedStatement ps = con.prepareStatement("UPDATE `"+talbeName+"` SET `STATUS`=5,`REMARK`=? WHERE `ID`=?");
			ps.setString(1, remark);
			ps.setInt(2, id);
			return ps;
		});
	}

	public int updateTask(int id, double predictDistance, double predictCost) {
		//TaskDao.log.info("---------更新任务，id:{}，predictDistance:{}，predictCost:{}---------", id, predictDistance, predictCost);
		return this.jdbcTemplate.update(con -> {
			PreparedStatement ps = con
					.prepareStatement("UPDATE `"+talbeName+"` SET `STATUS`=1, `PREDICT_DISTANCE`=?,`PREDICT_COST`=? WHERE `ID`=?");
			ps.setDouble(1, predictDistance);
			ps.setDouble(2, predictCost);
			ps.setInt(3, id);
			return ps;
		});
	}

	public int updateTaskSu4(int id, double predictDistance, double predictCost,Timestamp timestamp,String json) {
		TaskDao.log.info("---------更新任务，id:{}，predictDistance:{}，predictCost:{}---------", id, predictDistance, predictCost);
		return this.jdbcTemplate.update(con -> {
			PreparedStatement ps = con
					.prepareStatement("UPDATE `"+talbeName+"` SET `STATUS`=1, `PREDICT_DISTANCE`=?,`PREDICT_COST`=? ,`END_TIME`= ?,`TRACK_POINTS`=?  WHERE `ID`=?");
			ps.setDouble(1, predictDistance);
			ps.setDouble(2, predictCost);
			ps.setTimestamp(3, timestamp);
			ps.setString(4, ZipUtil.compressBase64(json));
			ps.setInt(5, id);
			return ps;
		});
	}

	public int completeTask(int id, double actualDistance, double actualCost) {
		TaskDao.log.info("---------结束任务，id:{}，actualDistance:{}，actualCost:{}---------", id, actualDistance,
				actualCost);
		return this.jdbcTemplate.update(con -> {
			PreparedStatement ps = con.prepareStatement(
					"UPDATE `"+talbeName+"` SET `STATUS`=4,`ACTUAL_DISTANCE`=?,`ACTUAL_COST`=?,`END_TIME`=? WHERE `ID`=?");
			ps.setDouble(1, actualDistance);
			ps.setDouble(2, actualCost);
			ps.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
			ps.setInt(4, id);
			return ps;
		});
	}

	public int completeTaskV2(long id) {
		TaskDao.log.info("---------结束任务V2，id:{}",id);
		return this.jdbcTemplate.update(con -> {
			PreparedStatement ps = con.prepareStatement("UPDATE `"+talbeName+"` SET `STATUS`=4,    `VERSION_NUM`=1 ,`UPDATE_TIME`=? WHERE `ID`=?");
			ps.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
			ps.setLong(2, id);
			return ps;
		});
	}

	public int deleteTask(int id) {
		TaskDao.log.info("---------删除任务，id:{}---------", id);
		return this.jdbcTemplate.update(con -> {
			PreparedStatement ps = con.prepareStatement("DELETE FROM `"+talbeName+"` WHERE `ID`=?");
			ps.setInt(1, id);
			return ps;
		});
	}

	public TaskQueryResult detailTask(int id) {
		Integer wrapId = Integer.valueOf(id);
		TaskQueryResult result = this.cache.getIfPresent(wrapId);
		if (result != null) {
			return result;
		}
		//TaskDao.log.info("---------获取任务详情，id:{}---------", id);
		List<TaskModel> data = this.jdbcTemplate.query(con -> {
			PreparedStatement ps = con.prepareStatement(
					"SELECT `NAME`,`SETTTINGS`,`STATUS`,`MODE`,`PREDICT_DISTANCE`,`PREDICT_COST`,`ACTUAL_DISTANCE`,`ACTUAL_COST`,`AIRCRAFT_ID`,`START_TIME`,`AUTHOR_ID`,`AUTHOR_NAME`,`TRACK_POINTS`,`RECTANGLE_POINT`,`STANDBY_KEEP_CLEAR_ROUTE` FROM `"+talbeName+"` WHERE `ID`=?");
			ps.setInt(1, id);
			return ps;
		}, new RowMapper<TaskModel>() {

			@Override
			public TaskModel mapRow(ResultSet rs, int rowNum) throws SQLException {
				TaskModel task = new TaskModel();
				task.setName(rs.getString("NAME"));
				task.setSettings(rs.getString("SETTTINGS"));
				task.setStatus(rs.getInt("STATUS"));
				task.setMode(rs.getInt("MODE"));
				task.setPredictDistance(rs.getDouble("PREDICT_DISTANCE"));
				task.setPredictCost(rs.getDouble("PREDICT_COST"));
				task.setActualDistance(rs.getDouble("ACTUAL_DISTANCE"));
				task.setActualCost(rs.getDouble("ACTUAL_COST"));
				task.setAircraftId(rs.getInt("AIRCRAFT_ID"));
				task.setStartTime(rs.getTimestamp("START_TIME"));
				task.setAuthorId(rs.getInt("AUTHOR_ID"));
				task.setAuthorName(rs.getString("AUTHOR_NAME"));
				task.setTrackPoints(rs.getString("TRACK_POINTS"));
				task.setRectanglePoint(rs.getString("RECTANGLE_POINT"));
				task.setAvoidancePoint(rs.getString("STANDBY_KEEP_CLEAR_ROUTE"));
				return task;
			}
		});
		if (data == null || data.size() == 0) {
			result = TaskQueryResult.EMPTY;
		} else {
			result = new TaskQueryResult(1, data);
		}
		this.cache.put(wrapId, result);
		return result;
	}

	public int countTaskTotal() {
		return this.countTaskTotal(null);
	}

	public int countTaskTotal(String keywords) {
//		TaskDao.log.info("---------统计任务个数，keywords:{}---------", keywords);
		return this.jdbcTemplate.query(con -> {
			return this.generatePreparedStatement(keywords, -1, -1, null, null,
					new StringBuilder("SELECT COUNT(`ID`) FROM `"+talbeName+"`"), con);
		}, new ResultSetExtractor<Integer>() {
			public Integer extractData(ResultSet resultSet) throws SQLException, DataAccessException {
				if (resultSet.next()) {
					return resultSet.getInt(1);
				}
				return Integer.valueOf(0);
			}
		}).intValue();
	}

	private PreparedStatement generatePreparedStatement(String keywords, int pageNo, int pageSize, String sortField,
														String sortRule, StringBuilder sql, Connection con) throws SQLException {
		if (!StringUtil.isEmpty(keywords)) {
			sql.append(" WHERE `NAME` LIKE %?%");
		}
		if (!StringUtil.isEmpty(sortField)) {
			sql.append(" ORDER BY ?");
			if (!StringUtil.isEmpty(sortRule)) {
				sql.append(" ?");
			}
		}
		if (pageSize >= 1) {
			if (pageNo >= 1) {
				sql.append(" LIMIT ?,?");
			} else {
				sql.append(" LIMIT ?");
			}
		}
		PreparedStatement ps = con.prepareStatement(sql.toString());
		sql.delete(0, sql.length());
		if (!StringUtil.isEmpty(keywords)) {
			ps.setString(1, keywords);
			if (!StringUtil.isEmpty(sortField)) {
				ps.setString(2, sortField);
				if (!StringUtil.isEmpty(sortRule)) {
					ps.setString(3, sortRule.toUpperCase());
					if (pageSize >= 1) {
						if (pageNo >= 1) {
							ps.setInt(4, (pageNo - 1) * pageSize);
							ps.setInt(5, pageSize);
						} else {
							ps.setInt(4, pageSize);
						}
					}
				} else {
					if (pageSize >= 1) {
						if (pageNo >= 1) {
							ps.setInt(3, (pageNo - 1) * pageSize);
							ps.setInt(4, pageSize);
						} else {
							ps.setInt(3, pageSize);
						}
					}
				}
			} else {
				if (pageSize >= 1) {
					if (pageNo >= 1) {
						ps.setInt(2, (pageNo - 1) * pageSize);
						ps.setInt(3, pageSize);
					} else {
						ps.setInt(2, pageSize);
					}
				}
			}
		} else {
			if (!StringUtil.isEmpty(sortField)) {
				ps.setString(1, sortField);
				if (!StringUtil.isEmpty(sortRule)) {
					ps.setString(2, sortRule.toUpperCase());
					if (pageSize >= 1) {
						if (pageNo >= 1) {
							ps.setInt(3, (pageNo - 1) * pageSize);
							ps.setInt(4, pageSize);
						} else {
							ps.setInt(3, pageSize);
						}
					}
				} else {
					if (pageSize >= 1) {
						if (pageNo >= 1) {
							ps.setInt(2, (pageNo - 1) * pageSize);
							ps.setInt(3, pageSize);
						} else {
							ps.setInt(2, pageSize);
						}
					}
				}
			} else {
				if (pageSize >= 1) {
					if (pageNo >= 1) {
						ps.setInt(1, (pageNo - 1) * pageSize);
						ps.setInt(2, pageSize);
					} else {
						ps.setInt(1, pageSize);
					}
				}
			}
		}
		return ps;
	}

	public int countReadyTaskTotal() {
		return this.jdbcTemplate.query(con -> {
			return this.generateReadyPreparedStatement(new StringBuilder("SELECT COUNT(`ID`) FROM `"+talbeName+"`"), con, false);
		}, new ResultSetExtractor<Integer>() {
			public Integer extractData(ResultSet resultSet) throws SQLException, DataAccessException {
				if (resultSet.next()) {
					return resultSet.getInt(1);
				}
				return Integer.valueOf(0);
			}
		}).intValue();
	}

	public TaskQueryResult queryReadyTask() {
		int total = this.countReadyTaskTotal();
		if (total == 0) {
			return TaskQueryResult.EMPTY;
		}
		return new TaskQueryResult(total, this.jdbcTemplate.query(con -> {
			return this.generateReadyPreparedStatement(
					new StringBuilder("SELECT `ID`,`SETTTINGS`,`MODE`,`AIRCRAFT_ID`,`START_TIME` FROM `"+talbeName+"`"), con,
					true);
		}, new RowMapper<TaskModel>() {

			@Override
			public TaskModel mapRow(ResultSet rs, int rowNum) throws SQLException {
				TaskModel task = new TaskModel();
				task.setId(rs.getInt("ID"));
				task.setSettings(rs.getString("SETTTINGS"));
				task.setMode(rs.getInt("MODE"));
				task.setAircraftId(rs.getInt("AIRCRAFT_ID"));
				task.setStartTime(rs.getTimestamp("START_TIME"));
				return task;
			}
		}));
	}

	private PreparedStatement generateReadyPreparedStatement(StringBuilder sql, Connection con, boolean sort)
			throws SQLException {
		sql.append(" WHERE `STATUS`=0 AND `AIRCRAFT_ID` IS NOT NULL AND `START_TIME`<=?");
		if (sort) {
			sql.append(" ORDER BY `START_TIME` ASC");
		}
		PreparedStatement ps = con.prepareStatement(sql.toString());
		sql.delete(0, sql.length());
		ps.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
		return ps;
	}

	public int countTaskTotal4Status(int status) {
		return this.jdbcTemplate.query(con -> {
			return this.generatePreparedStatement4Status(status, new StringBuilder("SELECT COUNT(`ID`) FROM `"+talbeName+"`"),
					con, false);
		}, new ResultSetExtractor<Integer>() {
			public Integer extractData(ResultSet resultSet) throws SQLException, DataAccessException {
				if (resultSet.next()) {
					return resultSet.getInt(1);
				}
				return Integer.valueOf(0);
			}
		}).intValue();
	}

	public TaskQueryResult queryTask4Status(int status) {
		int total = this.countTaskTotal4Status(status);
		if (total == 0) {
			return TaskQueryResult.EMPTY;
		}
		return new TaskQueryResult(total, this.jdbcTemplate.query(con -> {
			return this.generatePreparedStatement4Status(status,
					new StringBuilder("SELECT `ID`,`AIRCRAFT_ID` FROM `"+talbeName+"`"), con, true);
		}, new RowMapper<TaskModel>() {

			@Override
			public TaskModel mapRow(ResultSet rs, int rowNum) throws SQLException {
				TaskModel task = new TaskModel();
				task.setId(rs.getInt("ID"));
				task.setAircraftId(rs.getInt("AIRCRAFT_ID"));
				return task;
			}
		}));
	}

	private PreparedStatement generatePreparedStatement4Status(int status, StringBuilder sql, Connection con,
															   boolean sort) throws SQLException {
		sql.append(" WHERE `STATUS`=? AND `AIRCRAFT_ID` IS NOT NULL");
		if (sort) {
			sql.append(" ORDER BY `START_TIME` ASC");
		}
		PreparedStatement ps = con.prepareStatement(sql.toString());
		sql.delete(0, sql.length());
		ps.setInt(1, status);
		return ps;
	}

	public int countNeedUpdateStatusTaskTotal() {
		return this.jdbcTemplate.query(con -> {
			return this.generateNeedUpdateStatusPreparedStatement(new StringBuilder("SELECT COUNT(`ID`) FROM `"+talbeName+"`"),
					con, false);
		}, new ResultSetExtractor<Integer>() {
			public Integer extractData(ResultSet resultSet) throws SQLException, DataAccessException {
				if (resultSet.next()) {
					return resultSet.getInt(1);
				}
				return Integer.valueOf(0);
			}
		}).intValue();
	}

	public TaskQueryResult queryNeedUpdateStatusTask() {
		int total = this.countNeedUpdateStatusTaskTotal();
		if (total == 0) {
			return TaskQueryResult.EMPTY;
		}
		return new TaskQueryResult(total, this.jdbcTemplate.query(con -> {
			return this.generateNeedUpdateStatusPreparedStatement(new StringBuilder("SELECT `ID` FROM `"+talbeName+"`"), con,
					true);
		}, new RowMapper<TaskModel>() {

			@Override
			public TaskModel mapRow(ResultSet rs, int rowNum) throws SQLException {
				TaskModel task = new TaskModel();
				task.setId(rs.getInt("ID"));
				return task;
			}
		}));
	}

	private PreparedStatement generateNeedUpdateStatusPreparedStatement(StringBuilder sql, Connection con, boolean sort)
			throws SQLException {
		sql.append(" WHERE `STATUS` IN(1,2,3) AND `AIRCRAFT_ID` IS NOT NULL");
		if (sort) {
			sql.append(" ORDER BY `START_TIME` ASC");
		}
		PreparedStatement ps = con.prepareStatement(sql.toString());
		sql.delete(0, sql.length());
		return ps;
	}

	public int countFreeModeTaskTotal() {
		return this.jdbcTemplate.query(con -> {
			return this.generateFreeModePreparedStatement(new StringBuilder("SELECT COUNT(`ID`) FROM `"+talbeName+"`"), con,
					false);
		}, new ResultSetExtractor<Integer>() {
			public Integer extractData(ResultSet resultSet) throws SQLException, DataAccessException {
				if (resultSet.next()) {
					return resultSet.getInt(1);
				}
				return Integer.valueOf(0);
			}
		}).intValue();
	}

	public TaskQueryResult queryFreeModeTask() {
		int total = this.countFreeModeTaskTotal();
		if (total == 0) {
			return TaskQueryResult.EMPTY;
		}
		return new TaskQueryResult(total, this.jdbcTemplate.query(con -> {
			return this.generateFreeModePreparedStatement(new StringBuilder("SELECT `ID` FROM `"+talbeName+"`"), con, true);
		}, new RowMapper<TaskModel>() {

			@Override
			public TaskModel mapRow(ResultSet rs, int rowNum) throws SQLException {
				TaskModel task = new TaskModel();
				task.setId(rs.getInt("ID"));
				return task;
			}
		}));
	}

	private PreparedStatement generateFreeModePreparedStatement(StringBuilder sql, Connection con, boolean sort)
			throws SQLException {
		sql.append(" WHERE `STATUS` IN(1,3) AND `MODE`=0 AND `AIRCRAFT_ID` IS NOT NULL");
		if (sort) {
			sql.append(" ORDER BY `START_TIME` ASC");
		}
		PreparedStatement ps = con.prepareStatement(sql.toString());
		sql.delete(0, sql.length());
		return ps;
	}

	public int countRunningTaskTotal() {
		return this.jdbcTemplate.query(con -> {
			return this.generateRunningPreparedStatement(new StringBuilder("SELECT COUNT(`ID`) FROM `"+talbeName+"`"), con,
					false);
		}, new ResultSetExtractor<Integer>() {
			public Integer extractData(ResultSet resultSet) throws SQLException, DataAccessException {
				if (resultSet.next()) {
					return resultSet.getInt(1);
				}
				return Integer.valueOf(0);
			}
		}).intValue();
	}

	public TaskQueryResult queryRunningTask() {
		int total = this.countRunningTaskTotal();
		if (total == 0) {
			return TaskQueryResult.EMPTY;
		}
		return new TaskQueryResult(total, this.jdbcTemplate.query(con -> {
			return this.generateRunningPreparedStatement(
					new StringBuilder("SELECT `ID`,`AIRCRAFT_ID`,`DETECTED_TASK_IDS` FROM `"+talbeName+"`"), con, true);
		}, new RowMapper<TaskModel>() {

			@Override
			public TaskModel mapRow(ResultSet rs, int rowNum) throws SQLException {
				TaskModel task = new TaskModel();
				task.setId(rs.getInt("ID"));
				task.setAircraftId(rs.getInt("AIRCRAFT_ID"));
				int i = 0;
				JSONArray detectedTaskIdArray = JSON.parseArray(rs.getString("DETECTED_TASK_IDS"));
				int size = detectedTaskIdArray.size();
				Set<String> detectedTaskIds = new HashSet<String>();
				while (i < size) {
					detectedTaskIds.add(detectedTaskIdArray.getString(i++));
				}
				task.setDetectedTaskIds(detectedTaskIds);
				return task;
			}
		}));


	}

	public int updateTaskStatusNew(int id ,String json) {
		int row=this.jdbcTemplate.update(con -> {
			PreparedStatement ps = con.prepareStatement("UPDATE `"+talbeName+"` SET `TRACK_POINTS`=?  WHERE `ID`=?");
			ps.setString(1, ZipUtil.compressBase64(json));
			ps.setInt(2, id);
			return ps;
		});
		return row;
	}

	private PreparedStatement generateRunningPreparedStatement(StringBuilder sql, Connection con, boolean sort)
			throws SQLException {
		sql.append(" WHERE `STATUS`=1 AND `AIRCRAFT_ID` IS NOT NULL");
		if (sort) {
			sql.append(" ORDER BY `START_TIME` ASC");
		}
		PreparedStatement ps = con.prepareStatement(sql.toString());
		sql.delete(0, sql.length());
		return ps;
	}

	public int countTopTaskTotal() {
		return this.jdbcTemplate.query(con -> {
			return this.generateTopPreparedStatement(new StringBuilder("SELECT COUNT(`ID`) FROM `"+talbeName+"`"), con, false);
		}, new ResultSetExtractor<Integer>() {
			public Integer extractData(ResultSet resultSet) throws SQLException, DataAccessException {
				if (resultSet.next()) {
					return resultSet.getInt(1);
				}
				return Integer.valueOf(0);
			}
		}).intValue();
	}

	public TaskQueryResult queryTopTask() {
		int total = this.countTaskTotal();
		if (total == 0) {
			return TaskQueryResult.EMPTY;
		}
		return new TaskQueryResult(total, this.jdbcTemplate.query(con -> {
			return this.generateTopPreparedStatement(new StringBuilder("SELECT `ID` FROM `"+talbeName+"`"), con, true);
		}, new RowMapper<TaskModel>() {

			@Override
			public TaskModel mapRow(ResultSet rs, int rowNum) throws SQLException {
				TaskModel task = new TaskModel();
				task.setId(rs.getInt("ID"));
				return task;
			}
		}));
	}

	private PreparedStatement generateTopPreparedStatement(StringBuilder sql, Connection con, boolean sort)
			throws SQLException {
		sql.append(" WHERE `STATUS` IN(1,2) AND `AIRCRAFT_ID` IS NOT NULL");
		if (sort) {
			sql.append(" ORDER BY `CREATE_TIME` DESC");
		}
		return con.prepareStatement(sql.toString());
	}

	public int countWorkingTaskTotal() {
		return this.jdbcTemplate.query(con -> {
			return this.generateWorkingPreparedStatement(new StringBuilder("SELECT COUNT(`ID`) FROM `"+talbeName+"`"), con,
					false);
		}, new ResultSetExtractor<Integer>() {
			public Integer extractData(ResultSet resultSet) throws SQLException, DataAccessException {
				if (resultSet.next()) {
					return resultSet.getInt(1);
				}
				return Integer.valueOf(0);
			}
		}).intValue();
	}

	public TaskQueryResult queryWorkingTask() {
		int total = this.countTaskTotal();
		if (total == 0) {
			return TaskQueryResult.EMPTY;
		}
		return new TaskQueryResult(total, this.jdbcTemplate.query(con -> {
			return this.generateWorkingPreparedStatement(new StringBuilder("SELECT `ID`,`AIRCRAFT_ID` FROM `"+talbeName+"`"),
					con, true);
		}, new RowMapper<TaskModel>() {

			@Override
			public TaskModel mapRow(ResultSet rs, int rowNum) throws SQLException {
				TaskModel task = new TaskModel();
				task.setId(rs.getInt("ID"));
				task.setAircraftId(rs.getInt("AIRCRAFT_ID"));
				return task;
			}
		}));
	}

	private PreparedStatement generateWorkingPreparedStatement(StringBuilder sql, Connection con, boolean sort)
			throws SQLException {
		sql.append(" WHERE `STATUS` IN(1,2,3) AND `AIRCRAFT_ID` IS NOT NULL");
		if (sort) {
			sql.append(" ORDER BY `START_TIME` ASC");
		}
		return con.prepareStatement(sql.toString());
	}

	public int updateDetectedTaskIds(int id, String detectedTaskIds) {
		TaskDao.log.info("---------修改当前任务已进行冲突检测任务ID列表，id:{}，detectedTaskIds:{}---------", id, detectedTaskIds);
		return this.jdbcTemplate.update(con -> {
			PreparedStatement ps = con.prepareStatement("UPDATE `"+talbeName+"` SET `DETECTED_TASK_IDS`=? WHERE `ID`=?");
			ps.setString(1, detectedTaskIds);
			ps.setInt(2, id);
			return ps;
		});
	}

	public List<TaskModel> queryTaskModel() {
		List<TaskModel> data = this.jdbcTemplate.query(con -> {
//			String sql="SELECT `ID`,`SETTTINGS`,`MODE`,`AIRCRAFT_ID`,`START_TIME`,`NAME` FROM `"+talbeName+"`" +
//					"  WHERE `STATUS`=0 and  `VERSION_NUM`=0 AND `AIRCRAFT_ID` IS NOT NULL AND `START_TIME`<= '" +new Timestamp(System.currentTimeMillis()) +"' LIMIT 20";

			String sql="SELECT `ID`,`SETTTINGS`,`MODE`,`AIRCRAFT_ID`,`START_TIME`,`NAME` FROM `"+talbeName+"`" +
					"  WHERE `STATUS`=0 and  `VERSION_NUM`=0 AND `AIRCRAFT_ID` IS NOT NULL AND `START_TIME`<= '" +new Timestamp(System.currentTimeMillis()) +"'";

//			log.info("查询任务sql：{}",sql);
			PreparedStatement ps = con.prepareStatement(sql);
			return ps;
		}, new RowMapper<TaskModel>() {
			@Override
			public TaskModel mapRow(ResultSet rs, int rowNum) throws SQLException {
				TaskModel task = new TaskModel();
				task.setId(rs.getInt("ID"));
				task.setSettings(rs.getString("SETTTINGS"));
				task.setMode(rs.getInt("MODE"));
				task.setAircraftId(rs.getInt("AIRCRAFT_ID"));
				task.setStartTime(rs.getTimestamp("START_TIME"));
				task.setName(rs.getString("NAME"));
				return task;
			}
		});
		data.forEach(a->{
			this.jdbcTemplate.execute("UPDATE `"+talbeName+"` SET `VERSION_NUM`=1 WHERE `ID`="+a.getId());
		});
		return data;
	}

	public int updateTaskStandbyKeepClearRoute(int id, String standbyKeepClearRoute) {
		//	TaskDao.log.info("---------修改任务状态，id:{}，standbyKeepClearRoute:{}---------", id, standbyKeepClearRoute);
		return this.jdbcTemplate.update(con -> {
			PreparedStatement ps = con.prepareStatement("UPDATE `"+talbeName+"` SET `STANDBY_KEEP_CLEAR_ROUTE`=? WHERE `ID`=?");
			ps.setString(1, standbyKeepClearRoute);
			ps.setInt(2, id);
			this.cache.invalidate(id);
			return ps;
		});
	}

	public int updateTaskSingel(int singelType, Integer takId) {
		return this.jdbcTemplate.update(con -> {
			PreparedStatement ps = con.prepareStatement("UPDATE `"+talbeName+"` SET `SIGNAL_TYPE`=? WHERE `ID`=?");
			ps.setInt(1, singelType);
			ps.setInt(2, takId);
			this.cache.invalidate(takId);
			return ps;
		});
	}

	public int restartTask(Integer taskId, Long times, Integer status) {
		int tempStatus;
		if(status != null ){
			tempStatus=status;
		} else {
			tempStatus = 0;
		}
		Timestamp timestamp=new Timestamp(System.currentTimeMillis());
		if(times != null){
			timestamp=new Timestamp(times);
		}
		Timestamp finalTimestamp = timestamp;
		return this.jdbcTemplate.update(con -> {
			PreparedStatement ps = con.prepareStatement("UPDATE `"+talbeName+"` set `STATUS`=?,`VERSION_NUM`=0,START_TIME= ? where ID = ? ; ");
			ps.setInt(1, tempStatus);
			ps.setTimestamp(2, finalTimestamp);
			ps.setInt(3, taskId);
			return ps;
		});
	}
}
